package com.cws4cloud.cws.mall.xsm.util;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 * Created by david on 15/12/27.
 */
public class XmlHelper {

    public static Document parseXmlStr(String xmlStr) {
        Document doc = null;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(new InputSource(new StringReader(xmlStr)));

        } catch (Exception e) {

        }
        return doc;
    }

    public static String getElementContent(Document document, String tagName) {
        if (document != null) {
            NodeList nodeList = document.getElementsByTagName(tagName);
            int size = nodeList.getLength();
            if (size > 0) {
                return nodeList.item(0).getTextContent();
            } else return null;
        }
        return null;

    }

    public static String getAttributeContent(Document document,String elementTag,String attrName)
    {
        if(document!=null)
        {
            try {
               return  document.getElementsByTagName(elementTag).item(0).getAttributes().getNamedItem("msg").getTextContent();
            }catch (Exception e)
            {

            }
        }
        return null;
    }

}
